﻿#include "mianwid.h"
#include <qfiledialog.h>
#include <QMessageBox>
#include <qimage.h>
#include <QFile>
#include <QCoreApplication>

MianWid::MianWid(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	m_alg = new VisualCommon();
}

MianWid::~MianWid()
{
}

void MianWid::on_pushButton_clicked()
{
	visAlgParam param = {};
	param.calibration = ui.lineEdit->text();
	param.dir = ui.comboBox->currentIndex();
	param.maxNum = 3;
	if (param.calibration.isEmpty()) {
		QMessageBox::warning(this, "ERROR", "标定文件不能为空");
	}
	int ret = m_alg->Init(param);
	if (ret != 0) {
		QMessageBox::warning(this, "ERROR", "初始化失败");
	} else {
		ui.label_9->setText("初始化成功");
	}

}
json_struct(RecRect,
	mapping(int, P1X);
mapping(int, P1Y);
mapping(int, P2X);
mapping(int, P2Y);
mapping(int, P3X);
mapping(int, P3Y);
mapping(int, P4X);
mapping(int, P4Y);
prop(&P1X, &P2X, &P3X, &P4X, &P1Y, &P2Y, &P3Y, &P4Y);
);

json_struct(RecResult,
	mapping(QList<RecRect>, rects);
prop(&rects);
)

void MianWid::on_pushButton_2_clicked()
{
	VisAlgInput input = {};
	VisAlgOutput output = {};
	Position pos = {};
	input.rgb = ui.lineEdit_2->text();
	input.depth = ui.lineEdit_3->text();
	input.sku.height = ui.spinBox_3->value();
	input.sku.width = ui.spinBox_2->value();
	input.sku.length = ui.spinBox->value();
	input.taskNum = 10;
	input.jig = 1;

	QFile file(QCoreApplication::applicationDirPath() + ui.lineEdit_4->text());
	QByteArray data;
	if (file.open(QIODevice::ReadOnly)) {
		data = file.readAll();
		file.close();
	} else {
		QMessageBox::warning(this, "ERROR", "识别结果文件打开失败");
		return;
	}

	RecResult box = {};
	QString text = QString("{\"rects\": %1}").arg(QString(data));
	box.fromJson(text.toUtf8());
	for (auto& iter : box.rects()) {
		BoxPoint p1 = {};
		p1.x1 = iter.P1X();
		p1.x2 = iter.P2X();
		p1.x3 = iter.P3X();
		p1.x4 = iter.P4X();
		p1.y1 = iter.P1Y();
		p1.y2 = iter.P2Y();
		p1.y3 = iter.P3Y();
		p1.y4 = iter.P4Y();
		input.boxs.append(p1);
	}
	m_alg->Caculate(input, pos, output);
	if (output.rgb.isEmpty()) {
		ui.label_9->setText(output.msg);
	} else {
		QImage img;
		img.loadFromData(output.rgb.toBase64());
		//img.load(input.rgb);
		ui.label_9->setText("");
		ui.label_9->setPixmap(QPixmap::fromImage(img));
	}
}

//void MianWid::on_toolButton_3_clicked()
//{
//	QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "/home", tr("All Files (*)"));
//	if (!fileName.isEmpty()) {
//		ui.lineEdit->setText(fileName);	
//	}
//}
void MianWid::on_toolButton_2_clicked()
{
	QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "/home", tr("All Files (*)"));
	if (!fileName.isEmpty()) {
		ui.lineEdit_2->setText(fileName);
	}
}
void MianWid::on_toolButton_3_clicked()
{
	QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "/home", tr("All Files (*)"));
	if (!fileName.isEmpty()) {
		ui.lineEdit_3->setText(fileName);
	}
}
